import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/utils/language/language_util.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';
import 'package:sinosheets/utils/toast_util.dart';

class EstimateLogic extends GetxController {
  TextEditingController countryController = TextEditingController();
  TextEditingController weightController = TextEditingController();
  TextEditingController lengthController = TextEditingController();
  TextEditingController widthController = TextEditingController();
  TextEditingController heightController = TextEditingController();
  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  Map selectCountry = {};

  void onCountryClick() async {
    GBUtils.hideKeyboard();

    var backData = await GBUtils.openCountryPage(selectCountry, isShowChina: false);
    if (backData.isNotEmpty) {
      LSUtil.saveSelectCountry(backData);
    }
    updateCountry(backData);
  }

  void updateCountry(Map country) {
    if (country.isNotEmpty) {
      selectCountry = country;
      if (LanguageUtil.isChinese()) {
        countryController.text = selectCountry['name'] ?? "";
      } else {
        countryController.text = selectCountry['nameEn'] ?? "";
      }
    }
    update();
  }

  /// 邮限选择
  String selectLimitText = "";

  bool get isLimitSelect {
    return selectLimitText.isNotEmpty;
  }

  void onProductClick() async {
    bool isDataReady = await getQueryMailLimit();
    if (isDataReady) {
      // var result = await MailLimitSheet.show(mailLimitList, selectMailList);
      // if (result != null) {
      //   bool isConfirm = result["confirm"] ?? false;
      //   if (isConfirm) {
      //     selectMailList = result["selectMailList"] ?? [];
      //     String limitText = "";
      //     for (var item in selectMailList) {
      //       if (limitText.isNotEmpty) {
      //         limitText += ';';
      //       }
      //       limitText += '${item['firstName']}(${item['mailLimitName']})';
      //     }
      //     selectLimitText = limitText;
      //     update();
      //   }
      // }
    }
  }

  /// 获取邮限列表
  List mailLimitList = [];
  List selectMailList = [];

  Future<bool> getQueryMailLimit() async {
    if (mailLimitList.isNotEmpty) {
      return true;
    }
    BaseResponse response = await LogisticsApis.queryMailLimit();
    if (response.isSuccess) {
      List dataList = response.data ?? [];
      if (dataList.isNotEmpty) {
        mailLimitList = [];
        for (var first in dataList) {
          first["show"] = false;
          List secondList = first["secondMailLimitVOS"] ?? [];
          if (secondList.isNotEmpty) {
            for (var second in secondList) {
              second["select"] = false;
              second["firstId"] = first["id"];
              second["firstName"] = first["mailLimitName"];
            }
          }
          mailLimitList.add(first);
        }
        if (mailLimitList.isNotEmpty) {
          return true;
        }
      }
    } else {
      ToastUtil.showText(response.msg);
    }
    return false;
  }

  /// 计算运费
  void onEstimateClick() async {
    GBUtils.hideKeyboard();
    if (selectCountry.isEmpty) {
      ToastUtil.showText("select_country".tr);
      return;
    }
    String weightText = weightController.text;
    if (weightText.isEmpty) {
      ToastUtil.showText("placeholder_weight".tr);
      return;
    }
    double weightValue = double.tryParse(weightText) ?? 0.0;
    if (weightValue <= 0) {
      ToastUtil.showText("placeholder_weight".tr);
      return;
    }

    Map<String, dynamic> params = {
      /// 仓库和国家
      "countryId": selectCountry['id'],

      /// 重量
      "weight": double.tryParse(weightValue.toStringAsFixed(2)),

      /// 固定参数
      "configFlag": 1,
      "sizeLimitFlag": 1,
      "mailLimitFlag": 1,
      "volumeConfigFlag": 1,
      "lineCurrencyFlag": 1,
      "lineDeclareFlag": 1,
      "feeConfigFlag": 1,
    };

    /// 长宽高
    String lengthText = lengthController.text;
    String widthText = widthController.text;
    String heightText = heightController.text;
    double lengthValue = double.tryParse(lengthText) ?? 0.0;
    if (lengthValue > 0) {
      params["length"] = double.tryParse(lengthValue.toStringAsFixed(2));
    }
    double widthValue = double.tryParse(widthText) ?? 0.0;
    if (widthValue > 0) {
      params["width"] = double.tryParse(widthValue.toStringAsFixed(2));
    }
    double heightValue = double.tryParse(heightText) ?? 0.0;
    if (heightValue > 0) {
      params["height"] = double.tryParse(heightValue.toStringAsFixed(2));
    }

    /// 邮限
    if (selectMailList.isNotEmpty) {
      params["mailLimitList"] = selectMailList.map((item) {
        return {
          "firstLimitId": item["firstId"],
          "secondLimitId": item["id"],
        };
      }).toList();
    }

    GBUtils.openShippingLine(params);
  }
}
